package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R addCategory(@RequestBody Category category){
        categoryService.save(category);
         return R.success("新增成功");
    }


    @GetMapping("/page")
    public R pageCategory(int page,int pageSize){
        Page<Category> pageInfo = new Page<>(page, pageSize);
        categoryService.page(pageInfo);
        long all = pageInfo.getTotal();
        List<Category> records = pageInfo.getRecords();
        Map map = new HashMap();
        map.put("records",records);
        map.put("total",all);
        return R.success(map);
    }


    @DeleteMapping
    public R deleteCategory(Long id){
        categoryService.remove(id);
        return R.success("删除成功");
    }


    @PutMapping
    public R updateCategory(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改成功");
    }


    @GetMapping("/list")
    public R list(Integer type){
        LambdaQueryWrapper<Category> cqw = new LambdaQueryWrapper<>();
        cqw.eq(type!=null,Category::getType,type);
        cqw.orderByAsc(Category::getSort).orderByDesc(Category::getCreateTime);
        List<Category> list = categoryService.list(cqw);
        return R.success(list);
    }
}
